package com.mayn.jst.taobao;

import java.util.HashMap;
import java.util.LinkedHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mayn.jst.login.TaobaoLoginAction;
import com.mayn.jst.shop.action.ShopAccountAction;
import com.mayn.util.DateUtil;
import com.mayn.util.HttpUtil;
import com.mayn.util.ProcessUtil;
import com.mayn.util.SendCloudMailUtil;
import com.mayn.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 通过爬虫进行淘宝订单查询
 * 
 * @author Administrator
 *
 */
public class TaobaoOrderAction {

	private static final Logger LOG = LoggerFactory.getLogger(TaobaoOrderAction.class);

	private static String staticCookie = "";
	
	/**
	 * 授权
	 * @param cookie
	 * @param orderId
	 * @return
	 */
	public static JSONObject authUserInfo(String cookie) {
		
		try {
			String url = "https://trade.taobao.com/trade/security/auth_user_info.htm";

			HashMap<String, String> headers = new LinkedHashMap<String, String>();
			headers.put("accept", "application/json, text/javascript, */*; q=0.01");
			headers.put("accept-encoding", "gzip, deflate, br");
			headers.put("accept-language", "zh-CN,zh;q=0.8");
			headers.put("cache-control", "no-cache");
			headers.put("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
			headers.put("cookie", cookie);
			headers.put("pragma", "no-cache");
			headers.put("referer", "https://trade.taobao.com/trade/itemlist/list_sold_items.htm");
			headers.put("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3050.3 Safari/537.36");
			headers.put("x-requested-with", "XMLHttpRequest");

			LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
			long t = DateUtil.getUnixTime();
			double r = (Math.random() * (9999 - 1000 + 1)) + 1000;
			params.put("_ksTS", String.valueOf(t) + "_" + String.valueOf(Math.round(r)));


			String resp = HttpUtil.sendGetWithURLConnection(url, params, headers, "GBK");
			if (resp.startsWith("{")) {
				JSONObject object = JSONObject.fromObject(resp);
				return object;
			} else {
				t = DateUtil.getUnixTime();
				r = 10+ Math.random()*(99-10+1);
				params.put("_ksTS", String.valueOf(t) + "_" + String.valueOf(Math.round(r)));
				resp = HttpUtil.sendGetWithURLConnection(url, params, headers, "GBK");
				if (resp.startsWith("{")) {
					JSONObject object = JSONObject.fromObject(resp);
					return object;
				} else {
					int shopId = 5;
					if(TaobaoLoginAction.checkAndSaveTaobaoLoginCookie(5));
					{
						cookie = ShopAccountAction.getShopAccountCookie(shopId);
						headers.put("cookie", cookie);
						t = DateUtil.getUnixTime();
						r = 10+ Math.random()*(99-10+1);
						params.put("_ksTS", String.valueOf(t) + "_" + String.valueOf(Math.round(r)));
						resp = HttpUtil.sendGetWithURLConnection(url, params, headers, "GBK");
						if (resp.startsWith("{")) {
							JSONObject object = JSONObject.fromObject(resp);
							return object;
						} else {
							String msg = "淘宝订单查询授权错误:" + resp;
							SendCloudMailUtil.sendMailCode(msg, "dadao@iningmei.com");
							LOG.error(msg);
						}
					}
				}
			}
		} catch (Exception e) {
			String msg = "淘宝订单查询授权错误:" + e.getMessage();
			SendCloudMailUtil.sendMailCode(msg, "dadao@iningmei.com");
			LOG.error(msg);
		}
		return JSONObject.fromObject("{}");
	}
	
	/**
	 * 通过爬虫进行单个订单查询
	 * @param cookie
	 * @param orderId
	 * @return
	 */
	public static JSONObject SoldQueryAction(String cookie, String orderId) {

		try {
			String url = "https://trade.taobao.com/trade/itemlist/asyncSold.htm?event_submit_do_query=1&_input_charset=utf8";

			HashMap<String, String> headers = new LinkedHashMap<String, String>();
			headers.put("accept", "application/json, text/javascript, */*; q=0.01");
			headers.put("accept-encoding", "gzip, deflate, br");
			headers.put("accept-language", "zh-CN,zh;q=0.8");
			headers.put("cache-control", "no-cache");
			headers.put("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
			headers.put("cookie", cookie);
			headers.put("origin", "https://trade.taobao.com");
			headers.put("pragma", "no-cache");
			headers.put("referer", "https://trade.taobao.com/trade/itemlist/list_sold_items.htm");
			headers.put("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3050.3 Safari/537.36");
			headers.put("x-requested-with", "XMLHttpRequest");

			LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
			params.put("auctionType", "0");
			params.put("close", "0");
			params.put("pageNum", "1");
			params.put("pageSize", "15");
			params.put("queryMore", "true");
			params.put("rxAuditFlag", "0");
			params.put("rxHasSendFlag", "0");
			params.put("rxOldFlag", "0");
			params.put("rxSendFlag", "0");
			params.put("rxSuccessflag", "0");
			params.put("tradeTag", "0");
			params.put("useCheckcode", "false");
			params.put("useOrderInfo", "false");
			params.put("errorCheckcode", "false");
			params.put("action", "itemlist/SoldQueryAction");
			params.put("orderId", orderId);
			params.put("prePageNo", "1");
			params.put("buyerNick", "");
			params.put("dateBegin", "0");
			params.put("dateEnd", "0");
			params.put("logisticsService", "");
			params.put("orderStatus", "");
			params.put("queryOrder", "desc");
			params.put("rateStatus", "");
			params.put("refund", "");
			params.put("sellerNick", "");
			params.put("tabCode", "latest3Months");

			String resp = HttpUtil.sendPostWithURLConnection(url, params, headers, "GBK");
			if (resp.startsWith("{")) {
				JSONObject object = JSONObject.fromObject(resp);
				return object;
			} else {
				LOG.info("淘宝订单查询错误:延时1s再查询");
				ProcessUtil.ThreadSleep(1000);
				resp = HttpUtil.sendPostWithURLConnection(url, params, headers, "GBK");
				if (resp.startsWith("{")) {
					JSONObject object = JSONObject.fromObject(resp);
					return object;
				}else{
					LOG.info("淘宝订单查询错误:延时1s再查询");
					ProcessUtil.ThreadSleep(1000);
					resp = HttpUtil.sendPostWithURLConnection(url, params, headers, "GBK");
					if (resp.startsWith("{")) {
						JSONObject object = JSONObject.fromObject(resp);
						return object;
					}else{
						LOG.info("检查淘宝cookie再查询");
						int shopId = 5;
						if(TaobaoLoginAction.checkAndSaveTaobaoLoginCookie(5));
						{
							cookie = ShopAccountAction.getShopAccountCookie(shopId);
							headers.put("cookie", cookie);
							resp = HttpUtil.sendPostWithURLConnection(url, params, headers, "GBK");
							if (resp.startsWith("{")) {
								JSONObject object = JSONObject.fromObject(resp);
								return object;
							}else{
								LOG.info("强制获取淘宝cookie再查询");
								TaobaoLoginAction.ForceSaveTaobaoLoginCookie(5);
								cookie = ShopAccountAction.getShopAccountCookie(shopId);
								headers.put("cookie", cookie);
								resp = HttpUtil.sendPostWithURLConnection(url, params, headers, "GBK");
								if (resp.startsWith("{")) {
									JSONObject object = JSONObject.fromObject(resp);
									return object;
								}else{
									LOG.info("强制获取淘宝cookie任然查询失败");
								}
							}
						}
						String msg = "淘宝订单查询错误:" + resp;
						SendCloudMailUtil.sendMailCode(msg, "dadao@iningmei.com");
						LOG.error(msg);
					}
				}
			}
		} catch (Exception e) {
			String msg = "淘宝订单查询错误:" + e.getMessage();
			SendCloudMailUtil.sendMailCode(msg, "dadao@iningmei.com");
			LOG.error(msg);
		}
		return JSONObject.fromObject("{}");
	}
	
	
	/**判断是否村淘订单
	 * @param shopId
	 * @param orderId
	 * @return
	 */
	public static Boolean isCuntaoOrder(int shopId,String orderId){
		try{
			if(StringUtil.isBlank(staticCookie) ){
				if(TaobaoLoginAction.checkAndSaveTaobaoLoginCookie(shopId)){
					staticCookie = ShopAccountAction.getShopAccountCookie(shopId);
				}
			}
			if(!StringUtil.isBlank(staticCookie)){
				JSONObject authObject = TaobaoOrderAction.authUserInfo(staticCookie);
				if(authObject.containsKey("isNeedAuth") && !authObject.getBoolean("isNeedAuth")){
					JSONObject object = TaobaoOrderAction.SoldQueryAction(staticCookie,orderId);
					if(object.containsKey("mainOrders") && object.getJSONArray("mainOrders").size()>0){
						JSONArray mainOrders = object.getJSONArray("mainOrders");
						for(int i=0;i<mainOrders.size();i++){
							JSONObject mainOrder = mainOrders.getJSONObject(i);
							if(mainOrder.containsKey("subOrders") && mainOrder.getJSONArray("subOrders").size()>0){
								JSONArray subOrders =  mainOrder.getJSONArray("subOrders");
								for(int j=0;j<subOrders.size();j++){
									if(subOrders.getJSONObject(j).containsKey("itemInfo")){
										JSONObject itemInfo = subOrders.getJSONObject(j).getJSONObject("itemInfo");
										if(itemInfo.containsKey("serviceIcons")){
											JSONArray serviceIcons = itemInfo.getJSONArray("serviceIcons");
											for(int k=0;k<serviceIcons.size();k++){
												if(serviceIcons.getJSONObject(k).containsKey("linkUrl")){
													if(serviceIcons.getJSONObject(k).getString("linkUrl").contains("cun.taobao.com")){
														return true;
													}else{
														return false;
													}
												}
											}
										}
									}
								}
							}
						}
					}
					else{
						LOG.error("村淘订单查询:" + authObject.toString());
					}
				}else{
					LOG.error("村淘订单查询:" + authObject.toString());
				}
			}
			
		} catch (Exception e) {
			LOG.error("村淘订单查询错误:" + e.getMessage());
		}
		return null;
	}
	

}
